# -*- coding: utf-8 -*-
import math
import time
import json
import requests
import pymongo
from conf.settings import CLOUDMONITOR_MONGODB, CLOUDMONITOR_DB, MONITOR_API, UA
from utility.log import Logger
cloud = pymongo.MongoClient(CLOUDMONITOR_MONGODB)[CLOUDMONITOR_DB]
logger = Logger('batch_verify_asset.log').get_logger()


def verify(username):
    assert username, "username is error"
    logger.info(f'认证资产用户: {username}')
    url = f"{MONITOR_API['base_url']}/api/v2/jobs/verifications"
    headers = {
        'Cookie': f"token={MONITOR_API['token']}",
        'User-Agent': UA,
        'Content-Type': 'application/json'
    }
    user = cloud.users.find_one({'username': username})
    jobs = cloud.jobs.find({'uid': user['_id'], 'verification.isVerified': False}, {'_id': 1})
    job_ids = [str(_['_id']) for _ in jobs]
    if not job_ids:
        logger.info('没有需要认证的资产')
        exit(0)
    job_count = len(job_ids)
    for i in range(math.ceil(job_count / 10)):
        _job_ids = job_ids[i*10: (i+1) * 10]
        payload = json.dumps({
            "is_verified": True,
            "job_ids": _job_ids,
            "note": ""
        })
        response = requests.request("POST", url, headers=headers, data=payload, verify=False)
        logger.info(f'verify-{_job_ids}')
        logger.info(f'verify-{response.text}')
        time.sleep(1)
    logger.info(f'认证完成，共{job_count}个')


if __name__ == "__main__":
    _username = ''
    verify(_username)
